"use strict";

process.on("exit", () => {
  console.log();
});

if (!process.argv[2]) {
  throw new Error('[组件名]必填 - 请输入组件名')
}
if(!(/[a-zA-Z]+/g.test(process.argv[2]))) {
  throw new Error('[组件名]错误 - 请输入正确的组件名')
}
const path = require("path");
const fs = require("fs");
const fileSave = require("file-save");
const uppercamelcase = require("uppercamelcase"); // 转驼峰
const componentname = process.argv[2];
const ComponentName = uppercamelcase(componentname); // 转驼峰ComponentName
const packagesPath = path.resolve(__dirname, "packages", componentname); // packages文件夹路径
const componentsPath = path.resolve(__dirname, './packages/components/index.js')  // 全局组件路径
const navPath = path.join(__dirname, "./examples/nav.config.json"); // nav路径
const navLocationPath = "./examples/nav.config.json"
const mdPath = path.join(__dirname, './examples/docs/', `${componentname}.md`) // md路径
const cssPath = path.join(__dirname, './packages/theme-default/lib/', `${componentname}.less`) // less路径
const indexCssPath = path.join(__dirname, './packages/theme-default/lib/', `index.less`) // index css 路径

// 删除文件函数
function deleteFile(path) {
  if(fs.existsSync(path)) { // 文件存在才删除
    fs.unlinkSync(path)
  }
}
// 循环递归删除文件夹函数
function deleteFolder(path) {
  let files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach(function(file, index) {
      // 循环删除
      let curPath = path + "/" + file;
      if (fs.statSync(curPath).isDirectory()) {
        deleteFolder(curPath);
      } else {
        fs.unlinkSync(curPath);
      }
    });
    setTimeout(() => {
      fs.rmdirSync(path); // 只能删除空文件夹
    }, 200)
  }
}
// 删除全局组件和全局less
function deleteComponentAndLess(path, name) {
  let content = fs.readFileSync(path, "utf-8");
  let contentArr = content.split(/[\s]*\n[\s]*/);
  let reg = new RegExp(name, "g");
  contentArr.forEach((v, i) => {
    if (reg.test(v)) {
      contentArr.splice(i, 1);
    }
  });
  fs.writeFileSync(path, contentArr.join("\r\n"));
}
// 删除nav函数
function deleteNav(path) {
  const navConfigFile = require(path);
  let key = Object.keys(navConfigFile)[1];
  navConfigFile[key][0].items.forEach((v, i) => {
    if (v.name === componentname) {
      navConfigFile[key][0].items.splice(i, 1);
    }
  });
  fileSave(navPath).write(JSON.stringify(navConfigFile, null, '  '), 'utf8').end('\n');
}

// 删除nav
deleteNav(navLocationPath)

// 删除md文档
deleteFile(mdPath)

// 删除less
deleteFile(cssPath)

// 删除引入的全局组件
deleteComponentAndLess(componentsPath, ComponentName)

// 删除index css 路径
deleteComponentAndLess(indexCssPath, componentname)

// 删除packages对应文件夹
deleteFolder(packagesPath);

